#include "CardTemplate.h"

#include <QDebug>
#include <QStyle>

#include "ChartWidget.h"
#include "ConstData.h"
#include "System.h"
#include "operationWindow.h"
#include "ui_CardTemplate.h"
const QString style_success = "QLabel{color: #00ad7c;}";
const QString style_fail = "QLabel{color: #d84a4a;}";
const QString style_normal = "QLabel{color: #b1cdd4;}";
CardTemplate::CardTemplate(QWidget* parent) : QFrame(parent), ui(new Ui::CardTemplate)
{
    ui->setupUi(this);
}

CardTemplate::~CardTemplate() { delete ui; }

void CardTemplate::setData(const QString& title, const QString& unit)
{
    m_deviceId = title;
    ui->titleLabel->setText(title);
    ui->valueLabel->setText("---");
    ui->unitLabel->setText(unit);
    ui->statusLabel->setText("---");
    ui->commStatusLabel->setText("---");
    ui->statusLabel->setVisible(false);
    ui->label->setVisible(false);
    ui->faultCodeLabel->setStyleSheet(style_fail);
    auto helper = DeviceManager::instance()->getDeviceHelper(m_deviceId);
    if (helper) {
        auto attribute = helper->getDeviceAttribute();
        auto deviceType = attribute.deviceType;
        connect(helper, &IDevice::commStatusChanged, this, &CardTemplate::onCommStatusChanged);
        connect(helper, &IDevice::deviceDataChanged, this, &CardTemplate::onDeviceDataChanged);
        if (attribute.isShowData) {
            connect(this, &CardTemplate::clicked, this, [this]() {
                ChartWidget* chartWidget =
                    new ChartWidget(this, ChartDisplayMode::Window, m_deviceId);
                chartWidget->setAttribute(Qt::WA_DeleteOnClose);
                chartWidget->show();
            });
        }
        ui->statusLabel->setVisible(deviceType == DeviceType_normal);
        ui->faultCodeLabel->setVisible(deviceType == DeviceType_normal);
        ui->label->setVisible(deviceType == DeviceType_normal);
    }
}

void CardTemplate::setValue(const float& value, const QString& status, const QString& faultCode)
{
    ui->valueLabel->setText(QString::number(value, 'f', 3));
    ui->statusLabel->setText(status);
    ui->faultCodeLabel->setText(faultCode);
}
void CardTemplate::onCommStatusChanged(const bool& success)
{
    if (success) {
        ui->commStatusLabel->setText("✅ 正常");
        ui->commStatusLabel->setStyleSheet(style_success);
    } else {
        ui->commStatusLabel->setText("❌ 失败");
        ui->commStatusLabel->setStyleSheet(style_fail);
        ui->valueLabel->setText("---");
        ui->statusLabel->setText("---");
    }
}

void CardTemplate::onDeviceDataChanged(const DeviceData& data)
{
    ui->valueLabel->setText(QString::number(data.analyze_lastResult, 'f', 3));
    auto helper = DeviceManager::instance()->getDeviceHelper(m_deviceId);
    if (helper) {
        ui->statusLabel->setText(helper->getStatusName(data.status));
        ui->faultCodeLabel->setText(helper->getErrorName(data.faultCode));
    } else {
        ui->statusLabel->setText("---");
    }
}
void CardTemplate::changeEvent(QEvent* event)
{
    if (event->type() == QEvent::EnabledChange) {
        if (!isEnabled()) {
            ui->titleLabel->setText(m_deviceId + " (未启用)");
            ui->valueLabel->setText("---");
            ui->statusLabel->setText("---");
            ui->commStatusLabel->setText("---");
            ui->commStatusLabel->setStyleSheet(style_normal);
            ui->faultCodeLabel->setText("");
        } else {
            ui->titleLabel->setText(m_deviceId);
        }
    }
}
void CardTemplate::showEvent(QShowEvent* event)
{
    QFrame::showEvent(event);
    auto helper = DeviceManager::instance()->getDeviceHelper(m_deviceId);
    if (helper && helper->isEnabled()) {
        this->setEnabled(true);
    } else {
        this->setEnabled(false);
    }
}

void CardTemplate::hideEvent(QHideEvent* event)
{
    QFrame::hideEvent(event);
    auto system = System::instance();
    auto helper = DeviceManager::instance()->getDeviceHelper(m_deviceId);
    if (helper && !system->isRunning()) {
        // helper->stopDataMonitoring();
    }
}
void CardTemplate::mousePressEvent(QMouseEvent* event)
{
    if (event->button() == Qt::LeftButton && isEnabled()) {
        m_pressed = true;
        setProperty("pressed", true);
        style()->unpolish(this);
        style()->polish(this);

        // 添加按下时的位移效果
        if (layout()) {
            layout()->setContentsMargins(12, 12, 4, 4);
        }

        update();
    }
    QFrame::mousePressEvent(event);
}

void CardTemplate::mouseReleaseEvent(QMouseEvent* event)
{
    if (event->button() == Qt::LeftButton && m_pressed && isEnabled()) {
        m_pressed = false;
        setProperty("pressed", false);
        style()->unpolish(this);
        style()->polish(this);

        // 恢复正常位置
        if (layout()) {
            layout()->setContentsMargins(9, 9, 9, 9);
        }

        update();

        // 检查鼠标是否仍在控件内
        if (rect().contains(event->pos())) {
            emit clicked();
        }
    }
    QFrame::mouseReleaseEvent(event);
}

void CardTemplate::enterEvent(QEvent* event)
{
    if (isEnabled()) {
        setProperty("hovered", true);
        style()->unpolish(this);
        style()->polish(this);
        update();
    }
    QFrame::enterEvent(event);
}

void CardTemplate::leaveEvent(QEvent* event)
{
    if (isEnabled()) {
        m_pressed = false;
        setProperty("pressed", false);
        setProperty("hovered", false);
        style()->unpolish(this);
        style()->polish(this);

        // 恢复正常位置
        if (layout()) {
            layout()->setContentsMargins(9, 9, 9, 9);
        }

        update();
    }
    QFrame::leaveEvent(event);
}